package com.msb.mall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msb.common.utils.PageUtils;
import com.msb.common.utils.Query;
import com.msb.common.utils.R;
import com.msb.mall.product.dao.SkuInfoDao;
import com.msb.mall.product.entity.SkuImagesEntity;
import com.msb.mall.product.entity.SkuInfoEntity;
import com.msb.mall.product.entity.SpuInfoDescEntity;
import com.msb.mall.product.feign.SeckillFeignService;
import com.msb.mall.product.service.*;
import com.msb.mall.product.vo.SeckillVo;
import com.msb.mall.product.vo.SkuItemSaleAttrVo;
import com.msb.mall.product.vo.SpuItemGroupAttrVo;
import com.msb.mall.product.vo.SpuItemVO;
import com.mysql.cj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private SeckillFeignService seckillFeignService;

    @Autowired
    private ThreadPoolExecutor myThreadPoolExecutor;

    @Autowired
    private SkuImagesService imagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * sku 检索
     * 分类
     * 品牌
     * 价格区间 min max
     * key
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isNullOrEmpty(key)) {
            wrapper.and(item -> {
                item.eq("sku_id", key).or()
                        .like("sku_name", key);
            });
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isNullOrEmpty(catelogId)) {
            wrapper.and(item -> item.eq("catalog_id", catelogId));
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isNullOrEmpty(brandId)) {
            wrapper.and(item -> item.eq("brand_id", brandId));
        }
        String min = (String) params.get("min");
        if (!StringUtils.isNullOrEmpty(min)) {
            wrapper.and(item -> item.ge("price", min));
        }
        String max = (String) params.get("max");
        if (!StringUtils.isNullOrEmpty(max)) {
            BigDecimal bigMax = new BigDecimal(max);
            if (bigMax.compareTo(new BigDecimal(0)) == 1) {
                wrapper.and(item -> item.le("price", max));
            }
        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    /**
     * 商品详情
     *
     * @param skuId
     * @return
     */
    @Trace
    @Override
    public SpuItemVO item(Long skuId) throws ExecutionException, InterruptedException {
        SpuItemVO spuItemVO = new SpuItemVO();
        CompletableFuture<SkuInfoEntity> skuInfoFuture = CompletableFuture.supplyAsync(() -> {
            // 1.sku的基本信息 pms_sku_info
            SkuInfoEntity skuInfo = this.getById(skuId);
            spuItemVO.setInfo(skuInfo);
            return skuInfo;
        }, myThreadPoolExecutor);

        CompletableFuture<Void> imgsFuture = CompletableFuture.runAsync(() -> {
            // 2.sku的图片信息pms_sku_images
            List<SkuImagesEntity> imagesList = imagesService.list(new QueryWrapper<SkuImagesEntity>().eq("sku_id", skuId));
            spuItemVO.setImages(imagesList);
        }, myThreadPoolExecutor);

        CompletableFuture<Void> saleFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            // 3.获取spu中的销售属性的组合
            List<SkuItemSaleAttrVo> saleAttrs = skuSaleAttrValueService.querySaleAttrsBySpuId(res.getSpuId());
            spuItemVO.setSaleAttrs(saleAttrs);
        }, myThreadPoolExecutor);

        CompletableFuture<Void> descFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            // 4.获取SPU的介绍
            SpuInfoDescEntity spuDesc = spuInfoDescService.getById(res.getSpuId());
            spuItemVO.setDesc(spuDesc);
        }, myThreadPoolExecutor);

        CompletableFuture<Void> baseAttrFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            // 5.获取SPU的规格参数
            List<SpuItemGroupAttrVo> baseAttr = attrGroupService.queryAttrBycatelogId(res.getCatalogId(), res.getSpuId());
            spuItemVO.setBaseAttrs(baseAttr);
        }, myThreadPoolExecutor);

        CompletableFuture<Void> SeckillFuture = CompletableFuture.runAsync(() -> {
            // 秒杀信息
            R r = seckillFeignService.getSeckillSessionBySkuId(skuId);
            if (r.getCode() == 0) {
                String seckillInfo = JSON.toJSONString(r.get("seckillInfo"));
                SeckillVo seckillVo = JSON.parseObject(seckillInfo, SeckillVo.class);
                spuItemVO.setSeckillVO(seckillVo);
            }
        }, myThreadPoolExecutor);

        CompletableFuture.allOf(imgsFuture,saleFuture,baseAttrFuture,descFuture,SeckillFuture).get();
        return spuItemVO;
    }

}